package scau.zhong.mapper;

import org.apache.ibatis.annotations.*;
import scau.zhong.pojo.Permission;
import scau.zhong.pojo.Role;
import scau.zhong.pojo.User;
import tk.mybatis.mapper.common.Mapper;

import java.util.List;


public interface UserMapper extends Mapper<User> {

    @Select("select * from users where email = #{email}")
    @Results({
            @Result(id = true,property = "id",column = "id"),
            @Result(property = "roles",column = "id",javaType = List.class
                    ,many = @Many(select = "scau.zhong.mapper.UserMapper.queryRoleByUID") )//根据ID子查询
    })
    User findByEmail(@Param("email") String email);


    @Select("select * from users where username = #{username}")
    @Results({
            @Result(id = true,property = "id",column = "id"),
            @Result(property = "roles",column = "id",javaType = List.class
                    ,many = @Many(select = "scau.zhong.mapper.UserMapper.queryRoleByUID") )//根据ID子查询
    })
    User findByUsername(@Param("username") String username);

    @Select("select * from users")
    @Results({
            @Result(id = true,property = "id",column = "id"),
            @Result(property = "roles",column = "id",javaType = List.class
                    ,many = @Many(select = "scau.zhong.mapper.UserMapper.queryRoleByUID") )//根据ID子查询
    })
    List<User> findAll();

    /**
     * 根据用户ID查询用户角色
     * @param id
     * @return
     * 另一种写法，连接查询，select r.id,r.role_name,r.role_desc from role r,users_role ur where ur.userId = #{id} and ur.roleId = r.id
     * select * from role where id in (select roleId from users_role where userId = #{id})
     *
     */
    @Select("select r.id,r.role_name,r.role_desc from role r,users_role ur where ur.userId = #{id} and ur.roleId = r.id")
    List<Role> queryRoleByUID(@Param("id") String id);

    /**
     * 根据用户ID查询用户权限
     * @param id
     * @return
     */
    @Select("select * from permission where id in (select permissionId from role_permission WHERE roleId in (select id from role where id in (select roleId from users_role where userId = #{id})))")
    List<Permission> queryPermissionByUID(@Param("id") String id);

    /**
     * 新增用户-角色信息
     * @param uid
     * @param rid
     */
    @Insert("insert into users_role (userId,roleId) values (#{uid},#{rid})")
    Integer insertUser_Role(String uid, String rid);

    @Select("select COUNT(id) as amount from users where email=#{email};")
    Integer UserCountByEmail(@Param("email") String email);
}
